<template>
  <div class="drag-and-drop-container" @click="checkHit">
    <div class="large-boxes-container">
      <div v-for="(box, index) in largeBoxes" :key="'large-' + box?.prop" class="large-box"
        :class="{ 'box-highlight': highlightedBox === index, 'choose': parents[index].label == keyword }"
        @dragover.prevent @drop="handleDrop($event, index)" @dragenter="highlightBox(index)"
        @dragleave="unhighlightBox">
        <div class="title-id" @click="curParent = parents[index]">{{ parents[index].label }}</div>
        <div v-if="box" class="small-box" draggable="true" @dragstart="startDrag($event, box, index)"
          @click="curTag = box" @dragend="endDrag($event)" :style="{ backgroundColor: box.color }">
          <div class="box-id">{{ box.label }}</div>
        </div>
      </div>
    </div>
    <div class="small-boxes-container" @dragover.prevent @drop="handleDropToSmallBoxes">
      <div v-for="item in smallBoxes" :key="item.prop" class="small-box" draggable="true"
        @dragstart="startDrag($event, item)" @dragend="endDrag($event)"
        :style="{ backgroundColor: item.color, opacity: checkShow(item) }" @dblclick.stop="onFast(item)">
        <div class="box-id">{{ item.label }}</div>
      </div>
    </div>

    <div class="mt-4 flex items-center gap-2">
      <button @click="fastMatch" class="data-button text-nowrap mr-8">快速匹配</button>
      <span class="text-nowrap">属性</span> <el-input v-model="curTag.prop"></el-input>
      <span class="text-nowrap">字典</span>
      <el-select v-model="curTag.dicName" placeholder="Select">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <span class="text-nowrap">快速搜索</span> <el-switch v-model="curTag.search"></el-switch>
      <span class="text-nowrap">搜索序号</span> <el-input type="number" v-model="curTag.searchOrder"></el-input>
      <span class="text-nowrap">搜素默认值</span> <el-input v-model="curTag.searchValue"></el-input>
      <span class="text-nowrap">搜素标签宽度</span> <el-input v-model="curTag.searchLabelWidth"></el-input>

    </div>
    <div class="mt-4 flex items-center gap-2">
      <span class="text-nowrap">过滤</span> <el-input v-model="keyword"></el-input>

      <span class="text-nowrap">Label</span> <el-input v-model="dicObj.label"></el-input>
      <span class="text-nowrap">Value</span> <el-input v-model="dicObj.value"></el-input>
      <el-button @click="AddDic">添加字典</el-button>

      <span class="text-nowrap">Label</span> <el-input v-model="curParent.label"></el-input>
    </div>
    <div class="flex gap-4">
      <button @click="getBoxesData" class="data-button">获取数据</button>
    </div>

    <div v-if="boxesData" class="data-display">
      <textarea v-model="boxesData" class="w-full h-72 p-2 border border-gray-300 rounded-md mb-4"></textarea>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, defineProps, reactive } from 'vue';
const emits = defineEmits(["addItem", "changeLabel"])

interface IItem {
  // id: string;
  label: string;
  prop: string;
  color: string;
}

const props = defineProps({
  parents: {
    type: Array as () => IItem[],
    required: true
  },
  sons: {
    type: Array as () => IItem[],
    required: true
  }
});

const largeBoxes = ref<(IItem | null)[]>(Array(props.parents.length).fill(null));
const smallBoxes = ref<IItem[]>([]);
const highlightedBox = ref<number | null>(null);
const draggedItem = ref<IItem | null>(null);
const dragSourceIndex = ref<number | null>(null);
const boxesData = ref<any>(null);

const curTag = ref<any>({})
const keyword = ref("")
const options = ref<any[]>([])
const dicObj = reactive({ label: "", value: "" })

const curParent = ref<any>({})

const onFast = (item: any) => {
  console.log("双击", item)
  //把当前元素放入  label == keyword  的 large-box 内
  // 找到与 keyword 匹配的 large-box 的索引
  const targetIndex = props.parents.findIndex(parent => parent.label === keyword.value);

  // 如果找到了匹配的 large-box
  if (targetIndex !== -1) {
    // 将当前元素放入该 large-box
    if (!largeBoxes.value[targetIndex]) {
      // 如果目标 large-box 为空，直接放入
      largeBoxes.value[targetIndex] = item;
    } else {
      // 如果目标 large-box 已经有元素，将其移到 smallBoxes 中
      smallBoxes.value.push(largeBoxes.value[targetIndex]!);
      largeBoxes.value[targetIndex] = item; // 然后放入当前元素
    }

    // 从 smallBoxes 中移除当前元素（如果它在 smallBoxes 中）
    removeItemFromSmallBoxes(item);
  } else {
    console.warn("没有找到与 keyword 匹配的 large-box");
  }
}

const checkHit = (e: any) => {
  console.log(e)
  if (e.target.classList.contains("large-boxes-container")) {
    keyword.value = ""
  }
  if (e.target.classList.contains("title-id")) {
    keyword.value = e.target.innerText
  }
}

const AddDic = () => {
  if (dicObj.label && dicObj.value) {
    options.value.push({ ...dicObj })

    dicObj.label = ""
    dicObj.value = ""
  }
}


onMounted(() => {
  options.value = [
    { label: "未定义", value: "" },
    { label: "收货状态", value: "waiting_state" },
    { label: "质检状态", value: "qualitytest_state" },
    { label: "翻包状态", value: "pack_state" },
    { label: "上架状态", value: "pending_listed" },
  ]
})
const checkShow = (item: any) => {
  if (keyword.value) {
    return item.label.includes(keyword.value) ? 1 : 0.3
  }
  return 1
}

onMounted(() => {
  smallBoxes.value = props.sons.map((son: any, index) => ({
    ...son,
    label: son.name || son.label,
    color: getRandomColor()
  }));

  // fastMatch()
});

function sleep(ms: number) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function fastMatch() {
  for (let index = 0; index < props.parents.length; index++) {
    const temp = props.parents[index];
    keyword.value = temp.label
    await sleep(300)
    const item = smallBoxes.value.find(i => i.label == temp.label);
    if (item) {
      onFast(item);
    }
    await sleep(100)
  }
}

function getRandomColor() {
  const randomColor = Math.floor(Math.random() * 16777215).toString(16);
  return `#${randomColor.padStart(6, '0')}`;
}

function startDrag(event: DragEvent, item: IItem, sourceIndex: number | null = null) {
  draggedItem.value = item;
  dragSourceIndex.value = sourceIndex;
  event.dataTransfer!.effectAllowed = 'move';
  (event.target as HTMLElement).classList.add('dragging');
}

function endDrag(event: DragEvent) {
  (event.target as HTMLElement).classList.remove('dragging');
}

function handleDrop(event: DragEvent, targetIndex: number) {
  event.preventDefault();
  unhighlightBox();
  moveItem(draggedItem.value, targetIndex);
}

function handleDropToSmallBoxes(event: DragEvent) {
  event.preventDefault();
  if (draggedItem.value && dragSourceIndex.value !== null) {
    largeBoxes.value[dragSourceIndex.value] = null;
    smallBoxes.value.push(draggedItem.value);
  }
  resetDragState();
}

function moveItem(item: IItem | null, targetIndex: number) {
  if (!item) return;

  if (dragSourceIndex.value !== null) {
    // Moving from one large box to another
    largeBoxes.value[dragSourceIndex.value] = null;
  } else {
    // Moving from small boxes to a large box
    removeItemFromSmallBoxes(item);
  }

  // If there's already an item in the target large box, move it to small boxes
  if (largeBoxes.value[targetIndex]) {
    smallBoxes.value.push(largeBoxes.value[targetIndex]!);
  }

  // Add the item to the target large box
  largeBoxes.value[targetIndex] = item;
  resetDragState();
}

function removeItemFromSmallBoxes(item: IItem) {
  smallBoxes.value = smallBoxes.value.filter(i => i.prop !== item.prop);
}

function highlightBox(index: number) {
  highlightedBox.value = index;
}

function unhighlightBox() {
  highlightedBox.value = null;
}

function resetDragState() {
  draggedItem.value = null;
  dragSourceIndex.value = null;
}

function getBoxesData() {

  const list: any[] = []
  props.parents.forEach((parent, index) => {
    const obj: any = { ...largeBoxes.value[index] };

    if (obj.search) {
      obj.searchOrder = Number(obj.searchOrder)
      obj.searchLabelWidth = Number(obj.searchLabelWidth) || 100
      if (obj.searchValue) {
        obj.searchValue = Number(obj.searchValue)
      }
    }

    if (obj.dicName) {
      obj.type = "select";
      obj.dicUrl = "/system/dict/dictionary?code=" + obj.dicName;
      obj.props = {
        label: "dictValue",
        value: "dictKey"
      }
      delete obj.dicName
    }
    obj.name = parent.label;
    obj.label = parent.label;
    delete obj.color;
    delete obj.originLabel;
    list.push(obj)
  });

  boxesData.value = JSON.stringify(list, null, 2)

  navigator.clipboard.writeText(boxesData.value)
    .then(() => {
      console.log('文本已复制到剪贴板');
      // alert('文本已复制到剪贴板');
    })
    .catch(err => {
      console.error('复制失败:', err);
    });
}
</script>

<style scoped>
.drag-and-drop-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  padding: 20px;
  background-color: #f0f0f0;
  min-height: 100vh;
}

.large-boxes-container,
.small-boxes-container {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  justify-content: center;
}

.large-box {
  width: 100px;
  height: 100px;
  border: 2px solid #333;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  transition: all 0.3s ease;
  position: relative;
  flex-direction: column;
}

.small-box {
  width: 100%;
  height: 50px;
  margin: 5px;
  cursor: move;
  transition: all 0.3s ease;
  position: relative;
}

.box-highlight {
  background-color: rgba(0, 0, 0, 0.1);
  transform: scale(1.05);
}

.small-box:hover {
  transform: scale(1.1);
}

.small-boxes-container {
  min-height: 70px;
  border: 2px dashed #999;
  padding: 10px;
}

.small-boxes-container .small-box {
  width: 80px;
  height: 50px;
}

.box-id {
  position: absolute;
  width: 100%;
  font-size: 10px;
  background-color: rgba(255, 255, 255, 0.7);
}

.title-id {
  height: 30px;
  width: 100%;
  font-size: 10px;
  background: #333;
  color: #fff;
  padding: 4px;
}

.dragging {
  opacity: 0.5;
}

.data-button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.data-button:hover {
  background-color: #45a049;
}

.data-display {
  margin-top: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  width: 100%;
  overflow-x: auto;
}

.data-display h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.data-display pre {
  white-space: pre-wrap;
  word-wrap: break-word;
}

.choose {
  opacity: 0.7;
}
</style>